import { config } from "./config.js";
const App = getApp();

class HTTP {
	request({
		baseUrl = config.api_base_url,
		url,
		data = {},
		method = 'POST',
		header = {},
		callback = ""
	}) {
		// wx.showLoading({    //显示请求提示框
		// 	title: '请求中',
		// })
		let that = this;
		return new Promise((resolve, reject) => {
			wx.request({
				url: baseUrl + url,
				data: data,
				method: method,
				header: Object.assign(config.header, {
					'content-type': 'application/json',
					'Authorization': 'Bearer ' + App.globalData.token,
				}),
				success: result => {
					// console.log("请求统一结果：", url, result)
					if (callback) {
						// token过期后走这里，callback就是resolve
						callback(result.data.data);
						return;
					}

					if (result.data.code === 200) {
						resolve(result.data.data)
					}
					else if (result.data.code === 401) {
						// token过期，刷新token
						that._refreshToken().then(res => {
							that.request({ url, data, method, header, callback: resolve })
						})
					}
					else {
						reject()
						this._show_error(result.data.msg);
					}
				},
				fail: err => {
					reject()
					this._show_error(err);
				},
				complete() {
					// wx.hideLoading({})  //关闭请求提示框
				}
			})
		}).catch(function (error) {
			console.log("error: ", error)
		})
	}

	// 无感刷新token
	_refreshToken() {
		// console.log("调用无感刷新token: ")
		let that = this;
		return new Promise((resolve, reject) => {
			// 第一步：调用微信登陆，获取code
			wx.login({
				success: (res) => {
					// 第二步：通过code去登陆获取token
					that.request({ url: "/smp/login", data: { code: res.code } }).then(token => {
						if (token) {
							// 第三步：存储token
							App.globalData.token = token
							// 第四步：重新调用过期接口
							resolve()
						}
						else {
							return;
						}

					})
				},
				fail(err) {
					console.log(err)
				}
			})
		})

	}

	_show_error(error_msg) {
		let tip = '';
		error_msg ? tip = error_msg : tip = '抱歉，出现了一个错误';
		wx.showToast({
			title: tip,
			icon: 'none',
			duration: 2000
		})
	}
}

export {
	HTTP
}

